package hidalgo.expenses;

import hidalgo.expenses.entities.Session;
import hidalgo.expenses.utils.Constants;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

public class SessionManager extends Application {

	public static int sessionId = Constants.NO_ID;
	public static int userId = Constants.NO_ID;
	public static String token = Constants.NOT_LOGGED;

	public static Context context;

	@Override
	public void onCreate() {
		super.onCreate();

		context = this.getApplicationContext();
		Log.d("Session onCreate", "Session onCreate");
	}

	public static Boolean isLogged() {
		return !token.equals(Constants.NOT_LOGGED);
	}

	public static void login(Session session) {

		if (session != null) {
			sessionId = session.getSessionId();
			userId = session.getUserId();
			token = session.getToken();
		}

		persistLogin();
	}

	public static void logOut() {
		sessionId = Constants.NO_ID;
		userId = Constants.NO_ID;
		token = Constants.NOT_LOGGED;

		persistLogin();
	}

	public static void restoreLogin() {
		if(context!=null){
			// Restore preferences
			SharedPreferences settings = context.getSharedPreferences(
					Constants.PREFS_NAME, Context.MODE_PRIVATE);
	
			token = settings.getString("TOKEN", Constants.NOT_LOGGED);
			userId = settings.getInt("USERID", Constants.NO_ID);
			sessionId = settings.getInt("SESSION_ID", Constants.NO_ID);
		}
	}

	private static void persistLogin() {

		// We need an Editor object to make preference changes.
		SharedPreferences settings = context.getSharedPreferences(
				Constants.PREFS_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString("TOKEN", token);
		editor.putInt("USERID", userId);
		editor.putInt("SESSION_ID", sessionId);

		// Commit the edits!
		editor.commit();
	}
}
